package com.xcity.logupload.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class IOUtils {

	public static InputStream getResource(String name) {
		return Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
	}

	public static void closeQuietly(Closeable c) {
		if (c != null) {
			try {
				c.close();
			} catch (IOException e) {
			}
		}
	}

	public static void createDir(Path path) {
		if (!Files.exists(path)) {
			try {
				Files.createDirectories(path);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void batchDelete(Path path, boolean includeSelf) {
		try {
			if (!Files.exists(path)) {
				return;
			}
			if (Files.isDirectory(path)) {
				DirectoryStream<Path> ds = Files.newDirectoryStream(path);
				for (Path p : ds) {
					batchDelete(p, true);
				}
			}
			if (includeSelf) {
				Files.delete(path);
			}
			// Process p = null;
			// try {
			// p = Runtime.getRuntime().exec("rm -rf " + dir.getAbsolutePath() +
			// "/*");
			// p.waitFor();
			// } catch (Exception e) {
			// e.printStackTrace();
			// } finally {
			// if (p != null) {
			// p.destroy();
			// }
			// }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void copy(Path source, Path target) {
		try {
			Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void zip(File source, File target) {
		ZipOutputStream zos = null;
		try {
			zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target), 1024000));
			doZip("", source, zos);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeQuietly(zos);
		}
	}

	private static void doZip(String base, File source, ZipOutputStream zos) throws IOException {
		String entry = base + source.getName();
		if (source.isDirectory()) {
			for (File file : source.listFiles()) {
				doZip(entry + "/", file, zos);
			}
		} else {
			FileInputStream fis = null;
			BufferedInputStream bis = null;
			try {
				byte[] buffer = new byte[1024000];
				fis = new FileInputStream(source);
				bis = new BufferedInputStream(fis, buffer.length);
				int read = 0;
				zos.putNextEntry(new ZipEntry(entry));
				while ((read = bis.read(buffer, 0, buffer.length)) != -1) {
					zos.write(buffer, 0, read);
				}
				zos.closeEntry();
			} finally {
				closeQuietly(bis);
				closeQuietly(fis);
			}
		}
	}

}
